package cmd

import (
	"bufio"
	"encoding/json"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
)

func (tr *TaskRunner) CheckFileExist(filePath string) bool {
	if _, err := os.Stat(filePath); err != nil {
		return false
	}
	return true
}

func (tr *TaskRunner) WriteFile(filePath string, r io.Reader) (err error) {
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		os.MkdirAll(filepath.Dir(filePath), 0700) // Create your file
	}
	f, err := os.Create(filePath)
	if err != nil {
		slog.Errorf("create map file error: %v\n", err)
		return
	}
	defer f.Close()
	_, err = io.Copy(f, r)
	if err != nil {
		slog.Errorf("create map file error: %v\n", err)
		return
	}
	return
}

func (tr *TaskRunner) ReadLines(filePath string) (lines []string, err error) {
	f, err := os.Open(filePath)
	if err != nil {
		return
	}
	defer f.Close()
	scanner := bufio.NewScanner(f)

	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	return
}

func ReadJson[T any](filePath string) (r T, err error) {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return
	}
	var ptr = &r
	err = json.Unmarshal(data, ptr)
	return
}
